package com.mimc.framework.jwt;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import com.mimc.core.model.SysAdmin;
import com.mimc.core.service.SysAdminService;
import com.mimc.framework.core.RequestContextHolder;
import com.jfinal.aop.Aop;
import com.jfinal.aop.Inject;
import io.jboot.aop.annotation.Bean;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Bean
public class AdminTokenUtils {

    @Inject
    private SysAdminService sysAdminService;
    /**
     *
     * @param adminId 用户Id
     * @param sign 密钥
     * @param expireTime 过期时间
     * @return
     */
    public static String genToken(Long adminId,String sign,Integer expireTime){
        Date expiresAt= DateUtil.offsetSecond(new Date(),expireTime);
        String token = JWT.create()
                .setPayload("adminId", adminId)
                .setKey(sign.trim().getBytes())
                .setExpiresAt(expiresAt)
                .sign();
        return token;
    }

    //获取当前登录的用户信息
    public static SysAdmin getCurrentUser(){
        Integer userId=getCurrentUserId();

        if(userId==null){
            return null;
        }
        SysAdminService service = Aop.get(SysAdminService.class);
        return service.findById(userId);
    }
    public static Integer getCurrentUserId(){
        try{
            HttpServletRequest request = RequestContextHolder.get();
            String token = request.getHeader("token");

            if (StrUtil.isNotBlank(token)){
                JWT jwt = JWT.of(token);
                Integer userId= Integer.valueOf(jwt.getPayload("adminId").toString()) ;
                return userId;
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;

        }
        return null;
    }
    public static Boolean verifyToken(String token,String key){
        return JWT.of(token).setKey(key.trim().getBytes()).verify();
    }

    public static String getUserName(){
        SysAdmin sysAdmin=getCurrentUser();
        return sysAdmin.getUsername();
    }
}
